
import {plays, invoices} from "./data.js";

// 和第一版本进行对比
// 提炼函数，将积分计算单独封装
// 将返回结果同一修改为result
// 移除局部变量 format 格式化(format)，同时将除以100的逻辑也封装
// 拆分循环 volumeCredits
// 内联变量 totalVolumeCredits，移动语句 （将变量声明移动至循环语句处）
// 使用拆分循环和移动语句继续重构totalAmount

// 重构后的版本-V1.2
function statement (invoice, plays) {

  let result = `Statement for ${invoice.customer}\n`;
  for (let performance of invoice.performances) {
    // 打印订单
    // print line for this order
    result += ` ${playFor(performance).name}: ${usd(amountFor(performance))} (${performance.audience} seats)\n`;
  }
  result += `Amount owed is ${usd(totalAmount())}\n`;
  result += `You earned ${totalVolumeCredits()} credits \n`;

  return result;

  // 提炼函数，计算戏剧对应金额
  function amountFor(performance) {
    let result = 0;
    switch (playFor(performance).type) {
      case "tragedy":
        result = 40000;
        if (performance.audience > 30) {
          result += 1000 * (performance.audience - 30);
        }
        break;
      case "comedy":
        result = 30000;
        if (performance.audience > 20) {
          result += 10000 + 500 * (performance.audience - 20);
        }
        break;
      default:
        throw new Error(`unknown type: ${playFor(performance).type}`);
    }
    return result;
  }

  // 代码搬移，计算总金额
  function totalAmount() {
    let result = 0;
    for (let performance of invoice.performances) {
      result += amountFor(performance);
    }
    return result;
  }

  // 提炼函数，计算戏剧对应积分
  function volumeCreditsFor(performance) {
    let result = 0;
    // 增加积分
    // add volume credits
    result += Math.max(performance.audience - 30, 0);
    // 为什么是除以5呢？ 如果是除以10的话，大于5小于10的结果就是0
    // 如果是喜剧类型的戏剧，每多10个听众就增加1积分
    // add extra credit for every ten comedy attendees
    if ("comedy" === playFor(performance).type) {
      result += Math.floor(performance.audience / 5);
    }
    return result;
  }

  // 代码搬移，计算总积分
  function totalVolumeCredits() {
    let result = 0;
    for (let performance of invoice.performances) {
      result += volumeCreditsFor(performance);
    }
    return result;
  }

  // 消除局部变量play
  function playFor(performance) {
    return plays[performance.playID];
  }

  // 内联变量，格式化金额
  function usd(amount) {
    return new Intl.NumberFormat("en-US",
      {style: "currency", currency: "USD", minimumFractionDigits: 2}).format(amount / 100);
  }


}

for (let invoice of invoices) {
  // 18 19
  let result = statement(invoice, plays);
  console.log(result);
}





// 最后的效果是什么
